//
//  ImageSelectVC.swift
//  Automobile
//
//  Created by erkebulan elzhan on 8/19/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import UIKit



// MARK: - [Car Select View] mode comments

final class ImageSelectVC: UIViewController {
    
    // MARK: - Outlets

     private lazy var adPhotoBtn: UIButton = {
        let btn = UIButton()
        btn.clipsToBounds = true
        btn.layer.cornerRadius = 15
        btn.setTitle("Добавить фото", for: .normal)
        btn.backgroundColor = .blueColor
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel!.font = UIFont.systemFont(ofSize: 17, weight: .medium)
        return btn
    }()

    private lazy var cardView: CardView = {
        let cardView = CardView(text: "Объявление с фотографиями получает больше откликов, проследите чтобы на фото не было контактных данных и ссылок на сайты.", color: CardView.CardType.info)
        return cardView
    }()
    
    private lazy var placeholderImgView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.image = UIImage(named: "car_banner")
        return imageView
    }()
    
    private lazy var phototCollectionView: UICollectionView = {
        let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
        layout.sectionInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
        layout.itemSize = CGSize(width: 91, height: 91)
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.register(CarImageCell.self, forCellWithReuseIdentifier: "photoCell")
        collectionView.register(AddBtnCell.self, forCellWithReuseIdentifier: "addBtnCell")
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.backgroundColor = .clear
        return collectionView
    }()
    
    
    // MARK: - Props

    public weak var delegate: AdCreatorProtocol!
    
    
    private var images: [UIImage] = [] {
        didSet {
            self.navigationItem.title = "Фото \(images.count)/10"
            self.phototCollectionView.reloadData()
            if let cell = phototCollectionView.cellForItem(at: IndexPath(row: 0, section: 0)) as? AddBtnCell {
                cell.updateIcon(isDark: images.count == 10)
            }
        }
    }
    
    private var addedPhoto: Bool = false
    
    // MARK: - UI Actions
    
    @objc private func goBack(sender: UIBarButtonItem) {
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc private func closeVC (sender: UIBarButtonItem) {
        self.navigationController?.dismiss(animated: true, completion: nil)
        delegate.removeEverything()
    }
    @objc func onSubmit(sender: UIButton) {
        if !addedPhoto {
            showPickerController()
            addedPhoto = true
            adPhotoBtn.setTitle("Далее", for: .normal)
        } else {
            delegate.getImagesData(images: images)
            let descriptionVC = DesciptionViewController()
            descriptionVC.delegate = self.delegate
            self.navigationController?.pushViewController(descriptionVC, animated: true)
        }
    }

    
    // MARK: - Life-Cycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setUpUI()
        self.setUpNavBar()
    }

}

// MARK: - Methods


extension ImageSelectVC {
    private func showPickerController () {
        if !placeholderImgView.isHidden {
            self.showImgCollection()
        }
        
        let imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self
        imagePickerController.sourceType = .photoLibrary
        imagePickerController.allowsEditing = true
        self.present(imagePickerController, animated: true, completion: nil)
    }
}

// MAKR: - UI

extension ImageSelectVC {
    
    private func setUpUI () {
        view.backgroundColor = .white
        self.view.addSubview(cardView)
        self.view.addSubview(adPhotoBtn)

        adPhotoBtn.addTarget(self, action: #selector(onSubmit(sender:)), for: .touchUpInside)
        
        self.addCloseIcon()
        self.addConstraints()
        self.showPlaceholder()
    }
    
    private func addConstraints () {
        cardView.snp.makeConstraints { (make) in
            make.top.equalTo(view.safeAreaLayoutGuide).inset(30)
            make.leading.trailing.equalToSuperview().inset(16)
        }
        adPhotoBtn.snp.makeConstraints { (make) in
            make.leading.trailing.equalToSuperview().inset(16)
            make.bottom.equalTo(view.safeAreaLayoutGuide).offset(-16)
            make.height.equalTo(44)
        }
    }
    
    private func showImgCollection () {
        self.placeholderImgView.removeFromSuperview()
        placeholderImgView.isHidden = true
        self.view.addSubview(phototCollectionView)
        phototCollectionView.snp.makeConstraints { (make) in
            make.top.equalTo(cardView.snp.bottom).offset(30)
            make.leading.trailing.equalToSuperview().inset(16)
            make.bottom.equalTo(adPhotoBtn.snp.top).offset(-12)
        }
    }
    
    private func showPlaceholder () {
        self.view.addSubview(placeholderImgView)
        placeholderImgView.snp.makeConstraints { (make) in
            make.centerX.equalToSuperview()
            make.top.equalTo(cardView.snp.bottom).offset(48)
            make.leading.trailing.equalToSuperview().inset(50)
            make.height.equalTo((self.view.frame.width - 100)/1.95)
        }
    }
    
    private func setUpNavBar () {
//        let backIcon = UIImage(named: "cancel")
//        let backButton = UIBarButtonItem(image: backIcon, landscapeImagePhone: backIcon, style: .plain, target: self, action: #selector(goBack(sender:)))
//        backButton.tintColor = .greyColor
        
        self.navigationItem.title = "Фото"
        navigationItem.largeTitleDisplayMode = .always
        navigationController?.navigationBar.largeTitleTextAttributes = [
            NSAttributedString.Key.font: UIFont.systemFont(ofSize: 24, weight: .bold)
        ]
        navigationItem.hidesSearchBarWhenScrolling = false
        self.navigationController?.navigationItem.largeTitleDisplayMode = .always
    }
    
    private func addCloseIcon () {
        let closeBarBnt = UIBarButtonItem(image: UIImage(named: "dismiss"), style: .plain, target: self, action: #selector(closeVC))
        closeBarBnt.tintColor = .greyColor
        self.navigationItem.rightBarButtonItem = closeBarBnt
    }
}


extension ImageSelectVC: UICollectionViewDelegate, UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return images.count + 1
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        var cell: UICollectionViewCell!
        if indexPath.row == 0 {
            cell = collectionView.dequeueReusableCell(withReuseIdentifier: "addBtnCell", for: indexPath) as! AddBtnCell
        } else {
            cell = collectionView.dequeueReusableCell(withReuseIdentifier: "photoCell", for: indexPath) as! CarImageCell
            (cell as! CarImageCell).mediaView.putData(image: images[indexPath.row - 1], index: indexPath.row)
            (cell as! CarImageCell).mediaView.delegate = self
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if indexPath.row == 0 {
            if images.count == 10 {
                
            } else {
                self.showPickerController()
            }
        }
    }
    
}


extension ImageSelectVC: MediaViewProtocol {
    func removeImage(at index: Int) {
        images.remove(at: index - 1)
        phototCollectionView.reloadData()
    }
}


// MARK: - UI Image Picker Delegate

extension ImageSelectVC: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            self.images.append(pickedImage)
        }
        dismiss(animated: true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true, completion: nil)
    }
}


private class CarImageCell: UICollectionViewCell {
    
    public lazy var mediaView : MediaView = {
        let view = MediaView()
        return view
    }()

    override init(frame: CGRect) {
        super.init(frame: .zero)
        self.contentView.addSubview(mediaView)
        mediaView.snp.makeConstraints { (make) in
            make.leading.top.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

private class AddBtnCell: UICollectionViewCell {
    
    private lazy var imageAddBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "addImage"), for: .normal)
        btn.tag = 2
        btn.contentEdgeInsets = UIEdgeInsets(top: 11, left: 0, bottom: 0, right: 11)
        btn.isUserInteractionEnabled = false
        return btn
    }()
    
    public func updateIcon (isDark: Bool) {
        if isDark && imageAddBtn.alpha != 0.6 {
            imageAddBtn.alpha = 0.6
        } else if !isDark && imageAddBtn.alpha != 1 {
            imageAddBtn.alpha = 1
        }
    }
    

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.contentView.addSubview(imageAddBtn)
        imageAddBtn.snp.makeConstraints { (make) in
            make.leading.top.equalToSuperview()
            make.height.width.equalTo(91)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
